#!/bin/sh
# Copyright (c) 2011, bkil.hu
# This program is free software and can be distributed under the terms of
# the GNU General Public License v2,
# see COPYING for detailed licensing terms.

# created on 2011-05-06

main() {
 local L="1"
 while [ -n "$L" ]
 do
  local PIDS=`get_offenders`
  if [ -n "$PIDS" ] ;then
   if
    prompt
   then
    kill $PIDS
    sleep 5
   else
    exit 1
   fi
  else
   L=""
  fi
 done
 amixer sset 'CD' 100% # TV line playback volume
 exec tvtime
}

#TODO find a more elegant method of IPC?
prompt() {
 local PFILE=/tmp/tvtime_run_int.pid
 local RFILE=/tmp/tvtime_run_ret.pid
 rm $PFILE 2>/dev/null
 lxterminal -e 'bash -c "echo $$ > '${PFILE}'; echo 2 > '${RFILE}'; printf \"Mar fut egy felvetel.\n\nKet lehetoseg van:\n1. A felvetel folytatasahoz zarja be ezt az ablakot.\n2. ENTER benyomasa utan a felvetel leall es a TV indul el.\n\"; read R; [ -z \"$R\" ]; echo $? > '${RFILE}'"'
 local PID=""
 while [ -z "$PID" ] ;do
  PID=`cat "$PFILE" 2>/dev/null`
  sleep 0.1
 done
 while
  ! kill -s 0 $PID 2>/dev/null
 do
  sleep 0.1
 done
 while
  kill -s 0 $PID 2>/dev/null
 do
  sleep 0.1
 done
 RET=`cat "$RFILE" 2>/dev/null` ||exit 1
 rm $PFILE $RFILE ||exit 1
 echo $RET
 return $RET
}

get_offenders() {
# pidof tvtime
 local PIDS=""
 for a in `pidof mencoder` ;do
  if
   grep -qz '\<tv://' /proc/$a/cmdline ;then
   PIDS="$a $PIDS"
  fi
 done
 echo "$PIDS"
}

main "$@"
